package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.List;

/**
 * Created by WF on 2019/9/19 10:01
 */
@Service
public class SpitService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private SpitDao spitDao;
    //1.查询所有吐槽列表
    public List<Spit> findAll() {
        return spitDao.findAll();
    }
    //2.查询单个吐槽
    public Spit findById(String spitId) {
        return spitDao.findById(spitId).get();
    }
    //3.添加吐槽成功
    public void add(Spit spit) {
        //3.1)设置id
        spit.set_id(idWorker.nextId() + "");
        //3.2)添加吐槽
        spitDao.save(spit);
    }
    //4.修改吐槽
    public void update(Spit spit) {
        spitDao.save(spit);
    }
    //5.删除吐槽
    public void delete(String spitId) {
        spitDao.deleteById(spitId);
    }
    //6.根据父id查询吐槽列表
    public PageResult<Spit> findByParentId(String parentid, int page, int size) {
        //6.1)得到分页查询结果
        Page<Spit> spitPage = spitDao.findByParentid(parentid, PageRequest.of(page - 1, size));
        //6.2)将查询结果转换为PageResult对象
        return new PageResult<>(spitPage.getTotalElements(),spitPage.getContent());
    }
    //7.吐槽点赞(传统方法)
    public void updateThumbup(String spitId) {
        //7.1)得到原来的吐槽对象
        Spit spit = spitDao.findById(spitId).get();
        //7.2)修改其点赞数
        spit.setThumbup(spit.getThumbup() + 1);
        //7.3)执行修改操作
        spitDao.save(spit);
    }
    //7.吐槽点赞(mogoTemplate效率更高）
    public void updateThumbup2(String spitId) {
        //7.1)执行查询操作
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(spitId));
        //7.2)执行修改操作
        Update update = new Update();
        update.inc("thumbup",1);
        //7.3)使用模板执行修改操作
        mongoTemplate.updateFirst(query,update,"spit");
    }
}
